import os
import dify_helper
import pandas as pd
import argparse
import configparser
import pytesseract
import cv2
import imutils
import uuid
import requests
from pytesseract import Output

def read_img_and_auto_rotation(img_web_path:str):
    img_path = os.path.join("temp",str(uuid.uuid4())+".jpg")
    if not os.path.exists("temp"):
        os.mkdir("temp")
    r = requests.get(img_web_path)
    with open(img_path, 'wb') as f:
        f.write(r.content)
    img = cv2.imread(img_path)
    if img is None:
        return None
    # img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    try:
        results = pytesseract.image_to_osd(img, output_type=Output.DICT,config='--psm 0 -c min_characters_to_try=5')
        if results["rotate"] in [0,180,-180]:
            print("无需旋转")
            print(img_path)
            return img_path
        print("rotate:",results["rotate"])
        if results["rotate"] == 90:
            results["rotate"] = -90
        print(img_path)
        rotated = imutils.rotate_bound(img, angle=results["rotate"])
        cv2.imwrite(img_path, rotated)
    except:
        print("旋转失败")
        print(img_path)
        cv2.imwrite(img_path, img)
    return img_path

def run_dify(row:dict,query:str,dh:dify_helper.DifyHelper):
    if row["comment"] == None:
        return "无图片"
    rotated_img_path = read_img_and_auto_rotation(row["comment"])
    with open(rotated_img_path, "rb") as f:
        tmp_file_id = dh.upload_file({'file': (rotated_img_path, f, 'image/jpg')})
    paramters = {
        "image_path":{
            "type": "image",
            "transfer_method": "local_file",
            "upload_file_id": tmp_file_id
        },
    }
    # print(paramters)
    try:
        answer = dh.send_json_message(paramters,query)
    except Exception as ex:
        print(ex)
        answer = "解读失败"
    # print(answer)
    return answer

def run_dify_batch(data_excel_path:str,out_excel_path:str,dh:dify_helper.DifyHelper):
    data_df = pd.read_excel(data_excel_path)
    data_df['视觉模型识别结果'] = data_df.apply(lambda x:run_dify(x,"开始识别",dh),axis=1)
    data_df.to_excel(out_excel_path)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="dify批量运行器")
    parser.add_argument('-rep',"--raw_excel_path", type = str, help = "原始excel文件地址")
    parser.add_argument('-oep',"--out_excel_path", type = str, help = "输出excel文件地址")
    args = parser.parse_args()
    raw_excel_path = args.raw_excel_path
    out_excel_path = args.out_excel_path
    dh = dify_helper.DifyHelper("http://39.96.64.172:18863/v1","app-3gBWyKO79Htcby0xaXt1LFHW")
    run_dify_batch(raw_excel_path,out_excel_path,dh)